<template>
  <div class="add">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 提示文字区域 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :active="+active"
        finish-status="success"
        space="200px"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签页 -->
      <el-form
        v-if="active < 6"
        :model="FormData"
        :rules="rules"
        ref="ruleForm"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          :before-leave="toggle"
          @tab-click="tabClick"
          v-model="active"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="FormData.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="FormData.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="FormData.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="FormData.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器 -->
              <!-- option 指定数据源 -->
              <!-- prop 指定配置对象 -->
              <el-cascader
                v-model="selectKeys"
                :options="cateList"
                :props="cascaderProps"
                @change="parentCateChange"
                clearable
                class="cascader"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in manyData"
              :key="index"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item2"
                  v-for="(item2, index2) in item.attr_vals"
                  :key="index2"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in onlyData"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传组件 -->
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headers"
              :file-list="picList"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="FormData.goods_introduce" />
          </el-tab-pane>
        </el-tabs>
        <el-button
          v-if="active < 6"
          type="primary"
          class="submitbtn"
          @click="goNext"
          >{{ +active === 4 ? '提交' : '下一步' }}</el-button
        >
      </el-form>
      <div v-else-if="active === '6'" class="icon">
        <i class="el-icon-check"></i>
        <div class="txt">
          {{ goodId === '' ? '添加商品成功!' : '编辑成功!'
          }}{{ backTime }}秒后自动返回商品列表
        </div>
        <el-button class="submitbtn" @click="backGoods">返回商品列表</el-button>
      </div>
      <div v-else-if="active === '7'" class="icon">
        <i class="el-icon-check"></i>
        <div class="txt">操作失败!</div>
        <el-button class="submitbtn" @click="backGoods">返回商品列表</el-button>
      </div>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
      <img class="lookimg" :src="lookUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      dialogVisible: false,
      //  按钮文本
      btnname: '下一步',
      //  步骤条进度
      active: '0',
      //  表单数据
      FormData: {
        // 商品名称
        goods_name: '',
        //  商品价格
        goods_price: 0,
        // 商品重量
        goods_weight: 0,
        //  商品数量
        goods_number: 0,
        // 商品分类
        goods_cat: '',
        // attrs 静态属性和动态参数
        attrs: [],
        //  商品图片
        pics: [],

        //  商品介绍
        goods_introduce: ''
      },
      //  商品图片列表
      picList: [],
      //  级联选择器选择值
      selectKeys: [],
      //  级联选择器配置对象
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 级联选择器 商品分类数据列表
      cateList: [],
      //  商品参数数据列表
      manyData: [],
      //  商品属性
      onlyData: [],
      //  图片上传配置请求头token
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //  返回商品列表剩余时间
      backTime: 9,
      //  图片预览地址
      lookUrl: '',
      timerId: null,
      //  商品id
      goodId: +this.$route.query.id,
      // 商品图片编辑提交数据
      editpicdata: [],
      //  表单验证规则
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'change' }
        ]
      }
    }
  },
  mounted () {
    this.getCateList()
  },
  methods: {
    //  级联选择器获取商品分类数据列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('商品分类数据获取失败')
      this.cateList = res.data
    },
    // tab标签切换之前的钩子函数符合条件才切换
    toggle (news, old) {
      if (old === '0' && this.selectKeys.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    //  tab标签点击
    async tabClick () {
      //  请求商品参数
      if (this.active > '0') {
        const { data: res } = await this.$http.get(
          `categories/${this.selectKeys[2]}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        if (res.meta.status !== 200) return this.$message.error('获取失败')
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyData = res.data
      } else if (this.active > '1' && this.goodId === '') {
        //  请求商品属性
        const { data: res } = await this.$http.get(
          `categories/${this.selectKeys[2]}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        if (res.meta.status !== 200) return this.$message.error('获取失败')
        this.onlyData = res.data
      }
    },
    //  级联选择器change事件
    parentCateChange () {
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        return
      }
      this.FormData.goods_cat = this.selectKeys.join(',')
    },
    //  下一步按钮点击
    goNext () {
      if (this.selectKeys.length !== 3) {
        return this.$message.error('请先选择商品分类')
      }
      // 发起请求
      if (this.active === '4') {
        //  请求之前必填项预校验
        this.$refs.ruleForm.validate(async valid => {
          if (!valid) {
            this.active = '-1'
            return this.$message.error('请先填写必填项')
          }
          //  处理请求参数
          this.FormData.attrs = []
          this.manyData.forEach(item => {
            this.FormData.attrs.push({
              attr_id: item.attr_id,
              attr_value:
                item.attr_vals.length === 0 ? '' : item.attr_vals.join(' ')
            })
          })
          this.onlyData.forEach(item => {
            this.FormData.attrs.push({
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            })
          })
          //  商品id为空则是添加商品
          let res
          let message
          if (this.goodId === '') {
            res = await this.$http.post('goods', this.FormData)
            message = '添加成功'
          } else {

            //  编辑商品
            res = await this.$http.put(`goods/${this.goodId}`, this.FormData)
            message = '编辑成功'
          }
          if (res.data.meta.status !== 201 && res.data.meta.status !== 200) {
            this.active = '7'
            return this.$message.error('操作失败')
          }

          this.$message.success(message)
          this.active = '6'
          // 返回倒计时
          this.timerId = setInterval(() => {
            this.backTime--
            if (this.backTime === 0) {
              clearInterval(this.timerId)
              this.$router.push('/goods')
            }
          }, 1000)
        })
      }
      if (this.active > 4) return
      this.active++
      this.active = this.active + ''
      this.tabClick()
    },
    //  商品参数标签选中状态变化
    checkboxChange (i) {
      this.FormData.attrs.splice(i, 1)
    },
    // 文件上传---点击文件列表中已经上传的文件的钩子
    handlePreview (file) {
      //  打开预览弹窗
      this.dialogVisible = true
      //  预览地址赋值
      this.lookUrl = file.response.data.url
    },
    // 文件上传---文件列表移除文件时的钩子
    handleRemove (file) {
      // 文件移除将请求参数对象中对应的文件路径参数移除
      const i = this.FormData.pics.findIndex(
        item => item.pic === file.response.data.tem_path
      )
      this.FormData.pics.splice(i, 1)
    },
    //  文件上传---文件上传成功的钩子
    handleSuccess (res) {
      // 成功返回的图片push到请求参数图片数组中
      this.FormData.pics.push({
        pic: res.data.tmp_path
      })
    },
    //  点击返回商品列表
    backGoods () {
      clearInterval(this.timerId)
      this.$router.push('/goods')
    }
  },
  //  页面创建钩子
  async created () {
    // id有值则用户执行编辑操作 请求对应id的商品数据
    if (this.goodId) {
      const { data: res } = await this.$http.get(`goods/${this.goodId}`)
      // 显示图片列表图片赋值
      this.picList = res.data.pics.map(item => {
        return {
          name: item.pics_sma_url.split('/')[6],
          url: item.pics_sma_url,
          goods_id: item.goods_id
        }
      })
      //  更新图片参数处理
      res.data.pics.forEach(item => {
        this.editpicdata.push({
          goods_id: item.goods_id,
          pics_id: item.pics_id,
          pics_big: item.pics_big,
          pics_mid: item.pics_mid,
          pics_sma: item.pics_sma
        })
      })
      // 级联选择器赋值
      this.selectKeys = res.data.goods_cat.split(',').map(item => {
        return +item
      })
      // 属性和参数赋值
      res.data.attrs.forEach(item => {
        if (item.attr_sel === 'only') {
          this.onlyData.push(item)
        } else {
          this.manyData.push(item)
        }
      })
      for (let key in this.FormData) {
        if (key === 'pics' || key === 'attrs') {
          continue
        }
        this.FormData[key] = res.data[key]
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-steps {
  margin: 20px 0;
}
.el-tab-pane {
  padding-right: 130px;
  padding-left: 50px;
}
.lookimg {
  width: 100%;
}
.submitbtn {
  margin-top: 12px;
  margin-left: 150px;
  background-color: #823af1;
  color: #fff;
}
.icon {
  height: 400px;
  text-align: center;
  i {
    display: block;
    font-size: 100px;
    color: #67c23a;
    font-weight: 700;
  }
  .submitbtn {
    margin-top: 50px;
    margin-left: 0;
  }
}
</style>
